package com.personal.system.controller.sys;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import com.personal.common.result.Result;
import com.personal.system.entity.GenTable;
import com.personal.system.entity.GenTableColumn;
import com.personal.system.service.sys.GenTableColumnService;
import com.personal.system.service.sys.GenTableService;
import org.apache.commons.io.IOUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tool/gen")
public class GenController {

    @Resource
    private GenTableService genTableService;

    @Resource
    private GenTableColumnService genTableColumnService;

    @GetMapping("/list/{pageNum}/{pageSize}")
    public Result genList(@PathVariable int pageNum, @PathVariable int pageSize, GenTable genTable) {

        List<GenTable> list = genTableService.selectGenTableList(genTable);
        List<GenTable> pageList = ListUtil.page(pageNum - 1, pageSize, list);
        HashMap<String, Object> map = new HashMap<>();
        map.put("listMap", pageList);
        map.put("total", list.size());
        return Result.ok(map);
    }

    /**
     * 修改代码生成业务
     */
    @GetMapping(value = "/{talbleId}")
    public Result getInfo(@PathVariable Long talbleId) {
        GenTable table = genTableService.selectGenTableById(talbleId);
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
        Map<String, Object> map = new HashMap<>();
        map.put("info", table);
        map.put("rows", list);
        return Result.ok(map);
    }

    /**
     * 查询数据库列表
     */
    @GetMapping("/db/list/{pageNum}/{pageSize}")
    public Result dataList(@PathVariable Integer pageNum, @PathVariable Integer pageSize, GenTable genTable) {
        List<GenTable> list = genTableService.selectDbTableList(genTable);

        List<GenTable> pageList = ListUtil.page(pageNum - 1, pageSize, list);

        Map<String, Object> map = new HashMap<>();
        map.put("total", list.size());
        map.put("rows", pageList);
        return Result.ok(map);
    }

    /**
     * 查询数据表字段列表
     */
    @GetMapping(value = "/column/{talbleId}")
    public Result columnList(Long tableId) {
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);

        return Result.ok(list);
    }

    /**
     * 导入表结构（保存）
     */
    @PostMapping("/importTable")
    public Result importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return Result.ok();
    }

    /**
     * 修改保存代码生成业务
     */
    @PutMapping
    public Result editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return Result.ok();
    }

    /**
     * 删除代码生成
     */
    @DeleteMapping("/{tableIds}")
    public Result remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return Result.ok();
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview/{tableId}")
    public Result preview(@PathVariable("tableId") Long tableId) {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return Result.ok(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @GetMapping("/genCode/{tableName}")
    public Result genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return Result.ok();
    }

    /**
     * 同步数据库
     */
    @GetMapping("/synchDb/{tableName}")
    public Result synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return Result.ok();
    }

    /**
     * 批量生成代码
     */
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        this.genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
